package de.lot.action;

import de.lot.auth.PasswordBean;
import de.lot.auth.PasswordManager;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Begin;
import org.jboss.seam.annotations.web.RequestParameter;
import org.jboss.seam.framework.EntityHome;

import de.lot.model.LotUser;
import javax.persistence.EntityManager;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.In;
import org.jboss.seam.contexts.Context;
import org.jboss.seam.contexts.Contexts;
import org.jboss.seam.faces.FacesMessages;

/**
 * LosUserHome holds information needed by the form to show the user details.
 * 
 * @author Stefan Kohler <kohler.stefan@gmail.com>
 */
@Name("lotUserHome")
public class LotUserHome extends EntityHome<LotUser> {

    @RequestParameter
    Long lotUserId;
    @In
    FacesMessages facesMessages;

    public String createLotUser() {
        Context eventContext = Contexts.getEventContext();
        PasswordBean passwordBean = (PasswordBean) eventContext.get("passwordBean");
        if (!passwordBean.verify()) {
            facesMessages.addToControl("confirm", "Password has to match the repeat-section.");
            return null;
        }
        //LotUser newUser = (LotUser) Contexts.lookupInStatefulContexts("newUser");
        LotUser newUser = getInstance();
        PasswordManager passwordManager = (PasswordManager) Component.getInstance(PasswordManager.class);
        newUser.setPasswordHash(passwordManager.hash(passwordBean.getPassword()));

        EntityManager em = (EntityManager) Component.getInstance("entityManager");

        em.persist(newUser);

        facesMessages.add("Successfully created user: #{newUser.name}");

        return "success";
    }

    @Override
    public Object getId() {
        if (lotUserId == null) {
            return super.getId();
        } else {
            return lotUserId;
        }
    }

    @Override
    @Begin(join = true)
    public void create() {
        super.create();
    }
}
